package models

import (
	"github.com/astaxie/beego/orm"
)

type PjTypeModel struct {
	ID       int    `orm:"column(type_id);pk;auto"`
	TypeName string `orm:"column(type_name)"`
}

func (t *PjTypeModel) TableName() string {
	return "pj_type"
}

func init() {
	orm.RegisterModel(new(PjTypeModel))
}

func PjTypeAttributes() map[string]string {
	attributes := map[string]string{
		"ID":       "ID",
		"TypeName": "TypeName",
	}
	return attributes
}

func GetAllPjType() (ms []PjTypeModel, err error) {

	qb, err := orm.NewQueryBuilder("mysql")
	if err != nil {
		return ms, err
	}

	qb.Select("*").From("pj_type")
	o := orm.NewOrm()
	o.Raw(qb.String()).QueryRows(&ms)

	return ms, nil
}

func GetPjTypeById(id int) (PjTypeModel, error) {
	m := PjTypeModel{ID: id}
	o := orm.NewOrm()
	err := o.Read(&m)
	return m, err
}

func CreatePjType(m *PjTypeModel) (int, error) {
	o := orm.NewOrm()
	n, err := o.Insert(m)
	return int(n), err
}

func UpdatePjType(m *PjTypeModel) error {
	o := orm.NewOrm()
	v := PjTypeModel{ID: m.ID}
	if err := o.Read(&v); err != nil {
		return err
	}
	if _, err := o.Update(m); err != nil {
		return err
	}
	return nil
}

func DeletePjTypeById(id int) (int, error) {
	o := orm.NewOrm()
	v := PjTypeModel{ID: id}
	n, err := o.Delete(&v)
	return int(n), err
}

func SearchPjType(fields []string, limit int, offset int, orderby []string, sort string) []PjTypeModel {
	var f string
	var r string
	var ms []PjTypeModel
	qb, _ := orm.NewQueryBuilder("mysql")

	if len(fields) > 0 {
		for _, v := range fields {
			f = f + v
		}
		qb.Select(f).From("pj_type")
	} else {
		qb.Select("*").From("pj_type")
	}

	if len(orderby) > 0 {
		for _, v := range orderby {
			r = r + v
		}
		if sort == "ASC" || sort == "DESC" {
			qb.OrderBy(r + " " + sort)
		} else {
			qb.OrderBy(r)
		}
	} else {
		if sort == "ASC" || sort == "DESC" {
			qb.OrderBy(sort)
		}
		qb.OrderBy(r)
	}

	qb.Limit(limit).Offset(offset)

	sql := qb.String()

	o := orm.NewOrm()
	o.Raw(sql).QueryRows(&ms)
	return ms
}
